<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>重整序号-x.无空格</title>
    <style>
      #myTextarea,
      #myTextarea1 {
        width: 80%;
        min-height: 400px;
      }
    </style>
  </head>
  <body>
    <textarea id="myTextarea"></textarea>
    <button id="fetchContentButton">Renumber</button>

    <textarea id="myTextarea1"></textarea>
    <script>
      const textareaElement = document.getElementById('myTextarea');
      const textareaElement1 = document.getElementById('myTextarea1');
      const fetchContentButton = document.getElementById('fetchContentButton');

      function numLikk() {
        // Step 2: 获取textarea内容
        const textareaContent = textareaElement.value;

        // Step 3: 将内容保存到变量a
        let a = textareaContent;
        // console.log(a);
        let b = renumberAndFormatString2(a);
        textareaElement1.value = b;
        console.log(b);
      }

      function renumberAndFormatString2(input) {
        // Step 1: Split the input string into an array of lines
        const lines = input.split('\n');

        // Step 2: Process each line, extracting and updating the number
        const processedLines = lines.map((line, index) => {
          // Find the first occurrence of a digit followed by a dot (the actual number)
          const numberMatch = line.match(/\d+\./);
          if (!numberMatch) {
            throw new Error(`Invalid line format: ${line}`);
          }

          const numberStr = numberMatch[0];
          const contentStartIndex = numberMatch.index + numberStr.length;

          const currentNumber = parseInt(numberStr.replace('.', ''), 10);

          // Calculate the new number based on the position in the array
          const newNumber = index + 1;

          // Extract the content without the leading number and dot
          const content = line.slice(contentStartIndex).trim();

          // Add a Chinese period (。) at the end of the content if it doesn't already have one
          const formattedContent = content.endsWith('。')
            ? content
            : content + '。';

          // Return the updated line with the new number and formatted content
          return `${newNumber}.${formattedContent}`;
        });

        // Step 4: Join the processed lines back into a single string
        return processedLines.join('\n');
      }

      // 为按钮添加点击事件监听器
      fetchContentButton.addEventListener('click', numLikk);
    </script>
  </body>
</html>
